package com.longshen.dubbo.api.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.longshen.dubbo.api.anno.LoginRequired;
import com.longshen.dubbo.api.base.Contents;
import com.longshen.dubbo.api.base.ErrorCode;
import com.longshen.dubbo.api.base.SessionBean;
import com.longshen.dubbo.api.exception.DubboApiException;
import com.longshen.dubbo.api.tools.ServletTools;

import lombok.extern.slf4j.Slf4j;

/**
 * 检查登录状态
 * 
 * @author longshen
 *
 */
@Slf4j
@Component
public class LoginRequiredInterceptor extends HandlerInterceptorAdapter {
	

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
		
//		response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));//支持跨域请求
//        response.setHeader("Access-Control-Allow-Methods", "*");
//        response.setHeader("Access-Control-Allow-Credentials", "true");//是否支持cookie跨域
//        response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin, X-Requested-With, Content-Type, Accept,Access-Token");
//        
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();

		// 检查method是否有注解@LoginRequired
		// 如果有，则检查当前session是否已登录
		if (method.getAnnotation(LoginRequired.class) != null
				|| handlerMethod.getBeanType().getAnnotation(LoginRequired.class) != null) {
			HttpSession session = ServletTools.getSession(false);
			if (session == null) {
             // 用户未登录
				throw new DubboApiException(ErrorCode.E_000002);
			}

			SessionBean sessionBean = (SessionBean) session.getAttribute(Contents.SESSION_BEAN);
			if (sessionBean == null) {
				throw new DubboApiException(ErrorCode.E_000002);
			}

		}
		return true;
	}

}
